package edu.dlust.trading_platform;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import edu.dlust.trading_platform.DataBean.userdata;

public class ChatActivity extends AppCompatActivity {
    private static final String TAG = "ChatActivity";

    private ListView listView;
    private ArrayAdapter<String> adapter;
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private ImageView back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        listView = findViewById(R.id.listView_chat);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
        listView.setAdapter(adapter);

        back = findViewById(R.id.chat_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChatActivity.this.finish();
            }
        });

        EditText messageEditText = findViewById(R.id.editText_message);
        Button sendButton = findViewById(R.id.button_send);

        sendButton.setOnClickListener(v -> {
            String message = messageEditText.getText().toString();
            sendMessageToServer(userdata.getName()+": "+message);
            messageEditText.setText("");
            adapter.add(userdata.getName()+": "+message);
            listView.smoothScrollToPosition(adapter.getCount() - 1);
        });

        new ConnectToServer().execute();
    }

    private class ConnectToServer extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                socket = new Socket("frp.lsakura.top", 8888);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                String message;
                while ((message = in.readLine()) != null) {
                    Log.d(TAG, "Received message: " + message);
                    publishProgress(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            Log.d(TAG, "Updating UI with message: " + values[0]);
            adapter.add(values[0]);
            adapter.notifyDataSetChanged();
            listView.smoothScrollToPosition(adapter.getCount() - 1);
        }
    }

    private void sendMessageToServer(String message) {
        new Thread(() -> {
            if (out != null) {
                out.println(message);
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (socket != null) {
                socket.close();
            }
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}